<?php


namespace app\api\controller;


use app\api\validate\FamilyValidate;
use app\common\controller\Api;
use app\common\model\FamilyTree;
use app\common\model\FamilyTreeApply;
use app\common\model\FamilyTreeTem;
use think\Db;
use think\Exception;

class Family extends Api{
    protected $noNeedLogin = ['show'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 家庭树列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists(){
        $fId = request()->post('f_id');
        if(empty($fId)){
            $familyId = FamilyTree::where('user_id',$this->auth->id)->value('family_id');
            if(empty($familyId)){
                FamilyTree::create([
                    'user_id'   => $this->auth->id,
                    'family_id' => $this->auth->id,
                    'name'      => $this->auth->nickname,
                    'seniority' => $this->auth->seniority,
                    'seniority' => $this->auth->id,
                    'gender'    => $this->auth->gender,
                    'start_time'=> $this->auth->birthday,
                ]);
                $familyId = $this->auth->id;
            }
        }else{
            $familyId = FamilyTree::where('id',$fId)->value('family_id');
        }
        $data = [];
        $data['is_jz'] = $familyId == $this->auth->id ? 1 : 0;
        $data['f_id'] = FamilyTree::where('user_id',$this->auth->id)->value('id');
        if($data['is_jz'] != 1){
            $myFamilyInfo = FamilyTree::where('user_id',$this->auth->id)->find();
            $a1 = FamilyTree::where('parent_id',$myFamilyInfo['id'])->column('id');
            $a2 = FamilyTree::where('parent_id',$myFamilyInfo['id'])->where('spouse_id','<>',0)->column('spouse_id');
            $a1[] = FamilyTree::where('user_id',$this->auth->id)->value('id');
            if($myFamilyInfo['parent_id'] != 0){
                $a1[] = $myFamilyInfo['parent_id'];
                $parentInfo = FamilyTree::where('id',$myFamilyInfo['parent_id'])->find();
                if($parentInfo['spouse_id'] != 0){
                    $a1[] = $parentInfo['spouse_id'];
                }
            }
            if($myFamilyInfo['spouse_id'] != 0){
                $a1[] = $myFamilyInfo['spouse_id'];
                $myFamilyInfo = FamilyTree::where('id',$myFamilyInfo['spouse_id'])->find();
                $a3 = FamilyTree::where('parent_id',$myFamilyInfo['id'])->column('id');
                $a4 = FamilyTree::where('parent_id',$myFamilyInfo['id'])->where('spouse_id','<>',0)->column('spouse_id');
                $a3[] = FamilyTree::where('user_id',$this->auth->id)->value('id');
                if($myFamilyInfo['parent_id'] != 0){
                    $a3[] = $myFamilyInfo['parent_id'];
                    $parentInfo = FamilyTree::where('id',$myFamilyInfo['parent_id'])->find();
                    if($parentInfo['spouse_id'] != 0){
                        $a3[] = $parentInfo['spouse_id'];
                    }
                }
                $a1 = array_merge($a1,$a3,$a4);
            }
            $data['k_edit'] = array_merge($a1,$a2);
        }
        if(empty($familyId)){
            $this->success($data,[]);
        }
        $info = FamilyTree::getTree($familyId);
        $this->success($data,$info);
    }

    /**
     * 添加家庭成员
     * @throws \think\exception\DbException
     */
    public function add(){
        // type:1=添加配偶信息,2=添加上级,3=添加下级
        $post = request()->post();
        $validate = new FamilyValidate();
        if(!$validate->check($post)){
            $this->error($validate->getError());
        }
        $familyInfo = FamilyTree::get($post['f_id']);
        if(empty($familyInfo)){
            $this->error('参数错误');
        }
        if($post['status'] == 0 && (!isset($post['end_time']) || empty($post['end_time']))){
            $this->error('参数错误!');
        }
        if($familyInfo['family_id'] != $this->auth->id && $familyInfo['user_id'] != $this->auth->id){
            $this->error('不是家长无法添加');
        }
        Db::startTrans();
        try{
            if(empty($post['end_time'])){
                unset($post['end_time']);
            }
            $result = FamilyTree::create([
                'name'      => $post['name'],
                'seniority' => $post['seniority'],
                'spouse_id' => $familyInfo['id'],
                'gender'    => $post['gender'],
                'status'    => $post['status'],
                'family_id' => $familyInfo['family_id'],
                'start_time'=> $post['start_time'],
                'end_time'  => $post['end_time'] ?? NULL,
                'province'  => $post['province'] ?? '',
                'city'      => $post['city'] ?? '',
                'area'      => $post['area'] ?? '',
                'address'   => $post['address'] ?? '',
            ]);

            if($post['type'] == 1){
                // 添加配偶信息
                if($familyInfo['spouse_id'] != '0'){
                    throw new Exception('该用户已存在配偶');
                }
                if($familyInfo['gender'] == $post['gender']){
                    throw new Exception('配偶性别错误');
                }
                FamilyTree::where('id',$familyInfo['id'])->update(['spouse_id'=>$result['id']]);
            }elseif($post['type'] == 2){
                // 添加上级信息
                $fatherInfo = FamilyTree::get($familyInfo['parent_id']);
                if($post['gender'] == 1){
                    // 添加父亲
                    if(!empty($fatherInfo)){
                        throw new Exception('该用户已存在父亲');
                    }
                    FamilyTree::where('id',$result['id'])->update(['spouse_id'=>0]);
                    // 修改用户上级id
                    FamilyTree::where('id',$familyInfo['id'])->update(['parent_id'=>$result['id'],'is_max'=>0]);
                    // 修改家庭最上级
                    FamilyTree::where('id',$result['id'])->update(['is_max'=>1]);
                }else{
                    if(empty($fatherInfo)){
                        throw new Exception('请先添加父亲!');
                    }
                    // 添加母亲
                    if($fatherInfo['spouse_id'] != '0'){
                        throw new Exception('该用户母亲已存在!');
                    }
                    // 修改父母互相配偶id
                    FamilyTree::where('id',$result['id'])->update(['spouse_id'=>$fatherInfo['id']]);
                    FamilyTree::where('id',$fatherInfo['id'])->update(['spouse_id'=>$result['id']]);
                }

            }elseif($post['type'] == 3){
                // 添加下级信息
                if($familyInfo['gender'] == 1){
                    FamilyTree::where('id',$result['id'])->update(['parent_id'=>$familyInfo['id'],'spouse_id'=>0]);
                }else{
                    if($familyInfo['spouse_id'] != 0){
                        FamilyTree::where('id',$result['id'])->update(['parent_id'=>$familyInfo['spouse_id'],'spouse_id'=>0]);
                    }else{
                        FamilyTree::where('id',$result['id'])->update(['parent_id'=>$familyInfo['id'],'spouse_id'=>0]);
                    }
                }
            }
            Db::commit();
            FamilyTree::delCache($familyInfo['family_id']);
            $this->success('添加成功',$result);
        }catch(Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 编辑信息
     */
    public function edit(){
        $post = request()->post();
        if(empty($post['end_time']) || trim($post['end_time']) == 'null'){
            unset($post['end_time']);
        }
        $validate = new \think\Validate([
            'f_id'      => 'require',
            'name'      => 'require',
            'seniority' => 'require',
            'status'    => 'require|in:0,1',
            'start_time'=> 'require|dateFormat:Y-m-d',
            'end_time'  => 'requireIf:status,0|dateFormat:Y-m-d',
        ],[
            'f_id'      => '参数错误',
        ],[
            'name'      => '名称',
            'seniority' => '辈分',
            'status'    => '状态',
            'start_time'=> '出生日期',
            'end_time'  => '去世日期',
        ]);
        if(!$validate->check($post)){
            $this->error($validate->getError());
        }
        if(!in_array($post['gender'],[0,1])){
            $this->error('参数错误');
        }
        $familyInfo = FamilyTree::get($post['f_id']);
        if(empty($familyInfo)){
            $this->error('参数错误');
        }
        $myFamily = FamilyTree::where('user_id',$this->auth->id)->find();
        if(empty($myFamily)){
            $this->error('参数错误!');
        }
        // 当不是族长添加
        if($familyInfo['family_id'] != $this->auth->id){
            // 判断是否时我的上代与下代，或者是我自己
            $result = $this->checkFamily($familyInfo,$myFamily);
            if(!$result){
                if($myFamily['spouse_id'] != 0){
                    $spouse = FamilyTree::where('id',$myFamily['spouse_id'])->find();
                    $result = $this->checkFamily($familyInfo,$spouse);
                    if(!$result){
                        $this->error('权限不足，无法编辑');
                    }
                }else{
                    $this->error('权限不足，无法编辑');
                }
            }
        }
        //if($familyInfo['family_id'] != $this->auth->id && $familyInfo['user_id'] != $this->auth->id){
        //    $this->error('不是家长无法修改');
        //}
        //$selfFamilyId = FamilyTree::where('user_id',$this->auth->id)->value('family_id');
        //if($selfFamilyId != $familyInfo['family_id']){
        //    $this->error('参数错误!!');
        //}
        if($post['status'] == 1){
            unset($post['end_time']);
        }
        if($post['status'] == 0 && (!isset($post['end_time']) || empty($post['end_time']))){
            $this->error('参数错误!');
        }

        if($familyInfo['user_id'] != 0){
            $where = [
                'nickname'  => $post['name'],
                'seniority' => $post['seniority'],
                'birthday'  => $post['start_time'],
            ];
            if(isset($post['province']) && !empty($post['province']) && isset($post['city']) && !empty($post['city']) && isset($post['area']) && !empty($post['area'])){
                $where['province'] = $post['province'];
                $where['city'] = $post['city'];
                $where['area'] = $post['area'];
            }
            if(isset($post['address']) && !empty($post['address'])){
                $where['address'] = $post['address'];
            }
            if($post['status'] == 0){
                $where['die_time'] = $post['end_time'];
            }else{
                $where['die_time'] = NULL;
            }
            \app\common\model\User::where('id',$familyInfo['user_id'])->update($where);
        }

        $update = [
            'name'      => $post['name'],
            'seniority' => $post['seniority'],
            'status'    => $post['status'],
            'gender'    => $post['gender'],
            'start_time'=> $post['start_time'],
            'end_time'  => $post['end_time'] ?? NULL,
            'province'  => $post['province'] ?? '',
            'city'      => $post['city'] ?? '',
            'area'      => $post['area'] ?? '',
            'address'   => $post['address'] ?? '',
        ];
        FamilyTree::updateInfo($familyInfo,$update);
        FamilyTree::delCache($familyInfo['family_id']);
        $update['id'] = $familyInfo['id'];
        $this->success('修改成功',$update);
    }

    /**
     * 查看信息
     */
    public function show(){
        $fid = request()->post('f_id');
        if(empty($fid)){
            $info = FamilyTree::where('user_id',$this->auth->id)->find();
        }else{
            $info = FamilyTree::where('id',$fid)->find();
            if(empty($info)){
                $this->error('参数错误');
            }
            //$myInfo = FamilyTree::where('user_id',$this->auth->id)->find();
            //if(empty($myInfo) || $info['family_id'] != $myInfo['family_id']){
            //    $this->error('参数错误');
            //}
        }
        $this->success('请求成功',$info);
    }

    /**
     * 删除家庭成员
     */
    public function del(){
        $fId = request()->post('f_id');
        $familyInfo = FamilyTree::get($fId);
        if(empty($familyInfo)){
            $this->error('参数错误');
        }
        $myFamily = FamilyTree::where('user_id',$this->auth->id)->find();
        if(empty($myFamily)){
            $this->error('参数错误!');
        }
        // 当不是族长添加
        if($familyInfo['family_id'] != $this->auth->id){
            // 判断是否时我的上代与下代，或者是我自己
            $result = $this->checkFamily($familyInfo,$myFamily);
            if(!$result){
                if($myFamily['spouse_id'] != 0){
                    $spouse = FamilyTree::where('id',$myFamily['spouse_id'])->find();
                    $result = $this->checkFamily($familyInfo,$spouse);
                    if(!$result){
                        $this->error('权限不足，无法编辑');
                    }
                }else{
                    $this->error('权限不足，无法编辑');
                }
            }
        }
        if(FamilyTree::getChildZsyh($familyInfo['id'])){
            $childCount = FamilyTree::where('parent_id',$familyInfo['id'])->count();
            if($familyInfo['is_max'] == 1 && $childCount == 1){
                FamilyTree::where('parent_id',$familyInfo['id'])->update(['is_max'=>1,'parent_id'=>0]);
            }else{
                $this->error('用户已入驻或下级入驻,无法删除');
            }
        }
        FamilyTree::where('id',$fId)->delete();
        if($familyInfo['spouse_id'] != 0){
            FamilyTree::where('id',$familyInfo['spouse_id'])->delete();
        }
        FamilyTree::delCache($familyInfo['family_id']);
        $this->success('删除成功');
    }

    /**
     * 匹配家庭树
     */
    public function matching(){
        $name = request()->post('name');
        $name = explode('+',$name);
        if(empty($name[0]) || (!isset($name[1]) || empty($name[1]))){
            $this->error('请输入正确的搜索条件');
        }
        $info = Db::name('family_tree as fm1')
            ->join('family_tree fm2','fm1.spouse_id = fm2.id')
            ->where('fm1.name',$name[0])
            ->where('fm2.name',$name[1])
            ->field('fm1.id,fm1.name,fm1.spouse_id,fm1.seniority,fm1.parent_id,fm2.name as spouse_name')
            ->select();

        if($info->isEmpty()){
            $this->success('请求成功',[]);
        }
        $info = $info->toArray();
        foreach($info as $k=>$v){
            $info[$k]['father'] = FamilyTree::where('id',$v['parent_id'])->field('id,name,spouse_id,end_time')->find();
            $info[$k]['mother'] = [];
            if(!empty($info[$k]['father'])){
                $info[$k]['mother'] = FamilyTree::where('id',$info[$k]['father']['spouse_id'])->field('id,name,end_time')->find();
            }
        }
        $this->success('请求成功',$info);
    }

    /**
     * 提交家庭申请
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function apply(){
        $fId = request()->post('f_id');
        $selfFamil = FamilyTree::where('user_id',$this->auth->id)->find();
        $toFamily = FamilyTree::where('id',$fId)->find();
        if(empty($selfFamil) || empty($toFamily)){
            $this->error('错误请求');
        }
        if($selfFamil['family_id'] != $this->auth->id){
            $this->error('只有家庭长才能申请');
        }
        if($toFamily['family_id'] == $selfFamil['family_id']){
            $this->error('同家庭无法重复加入');
        }
        $count = FamilyTreeApply::where('apply_f_id',$selfFamil['id'])->where('status',0)->count();
        if($count > 0){
            $this->error('有未完成得申请，请勿重复申请');
        }
        FamilyTreeApply::create([
            'f_id'=>$fId,
            'apply_f_id'=>$selfFamil['id'],
            'family_id'=>$toFamily['family_id'],
            'user_id'   => $this->auth->id
        ]);
        $this->success('申请成功,请耐心等待对方审核');
    }

    /**
     * 家庭申请列表
     */
    public function applyList(){
        $familyInfo =  FamilyTree::where('user_id',$this->auth->id)->find();
        if($familyInfo['family_id'] != $this->auth->id){
            $this->error('不是家庭长,无法查看申请');
        }
        $apply = FamilyTreeApply::with('user,familyTree,familyTree.user')->where('family_id',$this->auth->id)->order('created_at','desc')->select();
        $this->success('请求成功',$apply);
    }

    /**
     * 进入家庭树(家庭长通过申请)
     */
    public function enter(){
        $applyId = request()->post('applyId');
        $fId = request()->post('f_id');
        $type = request()->post('type',1);
        if(empty($fId) || empty($applyId) || !in_array($type,[1,2])){
            $this->error('参数错误');
        }
        $applyInfo = FamilyTreeApply::where('id',$applyId)->where('status',0)->find();
        if(empty($applyInfo)){
            $this->error('申请不存在');
        }
        if($applyInfo['family_id'] != $this->auth->id){
            $this->error('无权限操作');
        }
        $familyInfo = FamilyTree::where('id',$fId)->field('id,seniority,family_id')->find();
        if($type == 1){
            if(empty($familyInfo) || $familyInfo['family_id'] != $this->auth->id){
                $this->error('家庭成员选择错误');
            }
        }

        $result = FamilyTree::apply($type,$familyInfo,$applyInfo);
        if(!$result){
            $this->error('审核失败,请联系管理员');
        }

        $this->success('加入成功');
    }


    /**
     * 搜索家庭内成员
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function searchInner(){
        $name = request()->post('name');
        $fId = request()->post('f_id');
        if(empty($name) || empty($fId)){
            $this->error('参数错误');
        }
        $myFamily = FamilyTree::where('id',$fId)->find();
        if(empty($myFamily)){
            $this->error('当前不存在家庭树');
        }
        $list = FamilyTree::where('family_id',$myFamily['family_id'])->where('name','like','%'. $name .'%')->field('id,name,end_time')->select();
        $this->success('请求成功',$list);
    }

    /**
     * 退出家庭树
     */
    public function retreatTree(){
        $myFamily = FamilyTree::where('user_id',$this->auth->id)->find();
        if(empty($myFamily)){
            $this->error('当前不存在家庭树');
        }
        Db::startTrans();
        try{

            $result = FamilyTree::where('id',$myFamily['id'])->update(['user_id'=>0]);
            if(!$result){
                throw new Exception('退出家庭树修改user_id失败');
            }

            FamilyTree::create([
                'user_id'   => $this->auth->id,
                'family_id' => $this->auth->id,
                'name'      => $this->auth->nickname,
                'seniority' => $this->auth->seniority,
                //'seniority' => $user->id,
                'gender'    => $this->auth->gender,
                'start_time'=> $this->auth->birthday,
                'is_max'    => 1,
            ]);

            FamilyTree::delCache($myFamily['family_id']);
            Db::commit();
            $this->success('退出成功');
        }catch(Exception $e){
            Db::rollback();
            write_log($e->getMessage(),'退出家庭树错误');
            $this->error();
        }
    }

    /**
     * 家庭申请未审核的数量
     * @throws Exception
     */
    public function applyCount(){
        $count = FamilyTreeApply::where('family_id',$this->auth->id)->where('status',0)->count();
        $this->success('请求成功',$count);
    }
}